/*
** file_generator.c for ftrace in /home/windel/Documents/Tek2/System_Unix/ftrace/pullup-project/sources
** 
** Made by nicolas simon
** Login   <simon_n@epitech.net>
** 
** Started on  Sun Jul  1 16:00:05 2012 nicolas simon
** Last update Sun Jul  1 17:37:12 2012 nathan vermelle
*/

#include		<sys/types.h>
#include		<sys/stat.h>
#include		<fcntl.h>
#include		<string.h>
#include		"../includes/ftrace.h"

void			add_in_token(char *name, t_token **tok)
{
  t_token		*tmp;
  t_token		*to_add;

  tmp = *tok;
  while (tmp && tmp->next)
    tmp = tmp->next;
  if ((to_add = malloc(sizeof(t_token))) == NULL)
    {
      write(2, "Error : malloc failed.\n", 23);
      exit (-1);
    }
  to_add->name = name;
  to_add->number = tmp->number + 1;
  tmp->next = to_add;
}

int			is_in(char *to_find, t_token *tok)
{
  t_token		*tmp;

  tmp = tok;
  while (tmp)
    {
      if (strcmp(tmp->name, to_find) == 0)
	return (1);
      tmp = tmp->next;
    }
  return (0);
}

void			pars_tree(t_tree *parent, t_tree *tree, t_token *tok, int fd)
{
  t_tree		*tmp;
  t_tree		**list;
  int			length;

  tmp = tree;
  if (tmp)
    {
      if (!is_in(tmp->name, tok))
	  add_in_token(tmp->name, &tok);
      if (parent)
	write(fd, make_string(get_token(tok, parent->name),
			      get_token(tok, tmp->name), &length), length);
      list = tmp->sons;
      while (list)
	{
	  pars_tree(tmp, *list, tok, fd);
	  ++list;
	}
    }
  write_database(tok, fd);
  close(fd);
}

void			make_file(t_tree *tree)
{
  t_tree		*tmp;
  t_token		*tokens;
  int			fd;

  tokens = NULL;
  tmp = tree;
  if ((fd = open("./graph.dot", O_CREAT | O_WRONLY | O_TRUNC,
		 S_IRWXU | S_IRWXG | S_IRWXO)) == -1)
    {
      write(2, "Error : file couldn't be created.\n", 34);
      exit (-1);
    }
  if (tmp)
    pars_tree(NULL, tmp, tokens, fd);
}
